package dubbo.server4.impl.mybatis;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class GenEntity {
	private String tablename = "user_repay_schedule";// 表名
	private String[] colnames; // 列名数组
	private HashMap<String, String> colnameComments; // 列名注释
	private String[] colTypes; // 列名类型数组
	private int[] colSizes; // 列名大小数组
	private boolean f_util = false; // 是否需要导入包java.util.*
	private boolean f_sql = false; // 是否需要导入包java.sql.*
	private List<String> ingoreColumn = new ArrayList<>();

	// 数据库连接
	private static final String URL = "jdbc:mysql://192.168.11.100:3306/hdy_loan?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull";
	private static final String NAME = "dev";
	private static final String PASS = "m9sbx^cW1xWa";
	private static final String DRIVER = "com.mysql.jdbc.Driver";

	/*
	 * 构造函数
	 */
	public GenEntity() {
		ingoreColumn.add("id");
		ingoreColumn.add("create_time");
		ingoreColumn.add("update_time");
		ingoreColumn.add("create_user_id");
		ingoreColumn.add("update_user_id");
		ingoreColumn.add("disabled");
		// 创建连接
		Connection con;
		// 查要生成实体类的表
		String sql = "select * from " + tablename;
		PreparedStatement pStemt = null;
		try {
			try {
				Class.forName(DRIVER);
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			con = DriverManager.getConnection(URL, NAME, PASS);
			pStemt = con.prepareStatement(sql);
			ResultSetMetaData rsmd = pStemt.getMetaData();
			int size = rsmd.getColumnCount(); // 统计列
			colnames = new String[size];
			colTypes = new String[size];
			colSizes = new int[size];
			colnameComments = new HashMap<>();
			ResultSet rs = con.getMetaData().getColumns(null, null, tablename, "%");
			while (rs.next()) {
				colnameComments.put(rs.getString("COLUMN_NAME"), rs.getString("REMARKS"));
			}
			for (int i = 0; i < size; i++) {
				colnames[i] = rsmd.getColumnName(i + 1);
				colTypes[i] = rsmd.getColumnTypeName(i + 1);
				String label = rsmd.getCatalogName(i + 1);
				System.out.println(label);
				if (colTypes[i].equalsIgnoreCase("datetime")) {
					f_util = true;
				}
				if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")) {
					f_sql = true;
				}
				colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
			}

			String content = parse(colnames, colTypes, colSizes);

			try {
				File directory = new File("");
				// System.out.println("绝对路径："+directory.getAbsolutePath());
				// System.out.println("相对路径："+directory.getCanonicalPath());
				String path = this.getClass().getResource("").getPath();

				System.out.println(path);
				System.out.println("src/?/" + path.substring(path.lastIndexOf("/com/", path.length())));
				FileWriter fw = new FileWriter(directory.getAbsolutePath() + "/src/main/java/"
						+ path.substring(path.lastIndexOf("/com/", path.length()), path.length()) + initTable(tablename)
						+ ".java");
				PrintWriter pw = new PrintWriter(fw);
				pw.println(content);
				pw.flush();
				pw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
		}
	}

	/**
	 * 功能：生成实体类主体代码
	 * 
	 * @param colnames
	 * @param colTypes
	 * @param colSizes
	 * @return
	 */
	private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
		StringBuffer sb = new StringBuffer();

		sb.append("package com.hdy.loan.common.mybatis.entity;\r\n");
		sb.append("import com.hdy.loan.common.mybatis.entity.BaseEntity;\r\n");
		sb.append("import com.hdy.loan.common.mybatis.annotation.Table;\r\n");
		sb.append("import java.io.Serializable;\r\n");
		sb.append("import java.math.BigDecimal;\r\n");
		// 判断是否导入工具包
		if (f_util) {
			sb.append("import java.util.Date;\r\n");
		}
		if (f_sql) {
			sb.append("import java.sql.*;\r\n");
		}
		sb.append("\r\n");
		// 注释部分
		sb.append("   /**\r\n");
		sb.append("    * " + tablename + " 实体类\r\n");
		sb.append("    * " + new Date() + "  \r\n");
		sb.append("    */ \r\n");
		// 实体部分
		sb.append("@Table(\"" + tablename + "\") \r\n");
		sb.append("public class " + initTable(tablename) + " extends BaseEntity implements Serializable {\r\n");
		processAllAttrs(sb);// 属性
		processAllMethod(sb);// get set方法
		sb.append("}\r\n");

		return sb.toString();
	}

	private String initTable(String tableName) {
		StringBuffer sb = new StringBuffer();
		if (tableName.contains("_")) {
			String[] c = tableName.split("_");
			for (int i = 0; i < c.length; i++) {
				char[] ch = c[i].toCharArray();
				if (ch[0] >= 'a' && ch[0] <= 'z') {
					ch[0] = (char) (ch[0] - 32);
				}
				sb.append(new String(ch));
			}
		} else {
			char[] ch = tableName.toCharArray();
			if (ch[0] >= 'a' && ch[0] <= 'z') {
				ch[0] = (char) (ch[0] - 32);
			}
			sb.append(new String(ch));
		}
		return sb.toString();
	}

	/**
	 * 功能：生成所有属性
	 * 
	 * @param sb
	 */
	private void processAllAttrs(StringBuffer sb) {
		for (int i = 0; i < colnames.length; i++) {
			if (ingoreColumn.contains(colnames[i])) {
				continue;
			}
			// 注释部分
			sb.append("   /**\r\n");
			sb.append("    * " + colnameComments.get(colnames[i]) + " \r\n");
			sb.append("    *  \r\n");
			sb.append("    */ \r\n");
			sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + initColumn(colnames[i]) + ";\r\n");
		}

	}

	private String initColumn(String column) {
		StringBuffer sb = new StringBuffer();
		if (column.contains("_")) {
			String[] c = column.split("_");
			for (int i = 0; i < c.length; i++) {
				if (i == 0) {
					sb.append(c[0]);
				} else {
					char[] ch = c[i].toCharArray();
					if (ch[0] >= 'a' && ch[0] <= 'z') {
						ch[0] = (char) (ch[0] - 32);
					}
					sb.append(new String(ch));
				}
			}
			return sb.toString();
		} else {

			return column;
		}
	}

	private String initSetGetColumn(String column) {
		StringBuffer sb = new StringBuffer();
		if (column.contains("_")) {
			String[] c = column.split("_");
			for (int i = 0; i < c.length; i++) {
				char[] ch = c[i].toCharArray();
				if (ch[0] >= 'a' && ch[0] <= 'z') {
					ch[0] = (char) (ch[0] - 32);
				}
				sb.append(new String(ch));
			}
			return sb.toString();
		} else {

			return captureName(column);
		}
	}

	/**
	 * 功能：生成所有方法
	 * 
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb) {

		for (int i = 0; i < colnames.length; i++) {
			if (ingoreColumn.contains(colnames[i])) {
				continue;
			}
			// 注释部分
			sb.append("   /**\r\n");
			sb.append("    * 设置 " + colnameComments.get(colnames[i]) + " \r\n");
			// sb.append(" * @param " + initColumn(colnames[i]) + " the " +
			// initColumn(colnames[i]) + " to set \r\n");
			sb.append("    */ \r\n");
			sb.append("\tpublic void set" + initSetGetColumn(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " "
					+ initColumn(colnames[i]) + "){\r\n");
			sb.append("\tthis." + initColumn(colnames[i]) + "=" + initColumn(colnames[i]) + ";\r\n");
			sb.append("\t}\r\n");
			sb.append("   /**\r\n");
			sb.append("    * 获取 " + colnameComments.get(colnames[i]) + " \r\n");
			// sb.append(" * @return the " + initColumn(colnames[i]) + " \r\n");
			sb.append("    */ \r\n");
			sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initSetGetColumn(colnames[i]) + "(){\r\n");
			sb.append("\t\treturn " + initColumn(colnames[i]) + ";\r\n");
			sb.append("\t}\r\n");
		}

	}

	/**
	 * 功能：将输入字符串的首字母改成大写
	 * 
	 * @param str
	 * @return
	 */
	private String initcap(String str) {

		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}

		return new String(ch);
	}

	/**
	 * 功能：获得列的数据类型
	 * 
	 * @param sqlType
	 * @return
	 */
	private String sqlType2JavaType(String sqlType) {

		if (sqlType.equalsIgnoreCase("bit")) {
			return "Boolean";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "Integer";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "Short";
		} else if (sqlType.equalsIgnoreCase("int")) {
			return "Integer";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return "Long";
		} else if (sqlType.equalsIgnoreCase("float")) {
			return "Float";
		} else if (sqlType.equalsIgnoreCase("decimal") ) {
			return "BigDecimal";
		}else if (sqlType.equalsIgnoreCase("numeric")
				|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
				|| sqlType.equalsIgnoreCase("smallmoney")) {
			return "Double";
		} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
				|| sqlType.equalsIgnoreCase("text")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("datetime")) {
			return "Date";
		} else if (sqlType.equalsIgnoreCase("date")) {
			return "Date";
		} else if (sqlType.equalsIgnoreCase("image")) {
			return "Blod";
		}

		return null;
	}

	/**
	 * 出口 TODO
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		new GenEntity();

	}

	public static String captureName(String name) {
		char[] cs = name.toCharArray();
		cs[0] -= 32;
		return String.valueOf(cs);

	}
}
